<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;

class Order extends Backend
{
    protected $OrderModel = null;
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->ProductModel = model('Product.Product');
        $this->AddressModel = model('Business.Address');
        $this->ExpressqueryModel = model('Expressquery');
        // 0、未支付 1、已支付 2、已发货 3、已收货 -1、退货
        $statuslist = [
            '0' => '未支付',
            '1' => '已支付',
            '2' => '已发货',
            '3' => '已收货',
            '-1' => '退货',
        ];
        $this->assign([
            'statuslist' => $statuslist,
        ]);
    }
    public function index()
    {
        // $list = $this->OrderModel
        //         ->with(['business'])
        //         ->select(); //查询数据

        // halt(collection($list)->toArray());
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->OrderModel
                ->with(['business', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->OrderModel
                ->with(['business', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo $this->OrderModel->getlastSql();
            // exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->OrderModel->with(['business', 'address'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        // halt($row->toArray());
        $this->assign("row", $row);

        $where = [
            'orderid' => $ids
        ];
        $OrderProductList = $this->OrderProductModel->where($where)->select();
        // halt(collection($OrderProductList)->toArray());

        if (!$OrderProductList) {
            $this->error(__('该商品不存在，请重新选择'));
        }
        // 商品数据
        // $productData=[];
        foreach ($OrderProductList as $item) {
            $product = $this->ProductModel->with(['type', 'unit'])->find($item['proid']);
            // $productData[] = [
            //     'id' => $item['proid'],
            //     'price' => $item['price'],
            //     'nums' => $item['pronum'],
            //     'total' => $item['total'],
            //     'product' => $product
            // ];
            $item['product'] = $product;

        }
        // halt(collection($productData)->toArray());
        $this->assignconfig('Product', ['OrderProductList' => $OrderProductList, 'business' => $row['business']]);

        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');
            // halt($params);

            $productList = json_decode($params['product'], true);
            $orderproid = array_column($productList, 'id');
            // foreach($OrderProductList as $item)
            // {

            // }
            // halt($orderproid);

            // exit;
            // halt($productList);

            // 更新订单表
            // 更新订单商品表或者插入商品表
            // 商品表更新库存

            // 加载模型
            $OrderModel = model("Order.Order");
            $OrderProductModel = model("Order.Product");
            $ProductModel = model("Product.Product");

            // 开启事务
            $OrderModel->startTrans();
            $OrderProductModel->startTrans();
            $ProductModel->startTrans();

            // 更新订单表数据
            $OrderData = [
                'id' => $ids,
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'businessaddrid' => $params['businessaddrid'],
                'status' => $params['status']
            ];
            // halt($OrderData);
            $OrderStatus = $OrderModel->isUpdate(true)->save($OrderData);
            if ($OrderStatus === FALSE) {
                $this->error('订单更新失败');
                exit;
            }

            // 更新或插入订单商品
            foreach ($productList as $item) {
                // 订单商品表没有，则插入
                if (!isset($item['id'])) {
                    // echo '<br/>'.$item['proid'].'插入数据';

                    $OrderProductData = [
                        'orderid' => $ids,
                        'proid' => $item['proid'],
                        'pronum' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                        'commentstatus' => '0',
                    ];
                    $OrderProductStatus = $OrderProductModel->save($OrderProductData);
                    if ($OrderProductStatus === FALSE) {
                        $OrderModel->rollback();
                        $this->error('订单商品添加失败');
                        exit;
                    }
                    // else
                    // {
                    //     $this->error('订单商品添加成功');
                    //     break;
                    // }
                }


            }
            // 有id且有修改则更新 得单独拎出来，不然插入不了订单数据
            foreach ($productList as $item) {
                if (isset($item['id'])) {
                    // echo '<br/>'.$item['id'].'更新';
                    $OrderProduct = $OrderProductModel->find($item['id']);
                    $OrderProductData = [
                        'id' => $item['id'],
                        'orderid' => $ids,
                        'proid' => $item['proid'],
                        'pronum' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                        'commentstatus' => $OrderProduct['commentstatus'],
                    ];
                    $OrderProductStatus = $OrderProductModel->validate('common/Order/Product')->isUpdate(true)->save($OrderProductData);
                    if ($OrderProductStatus === FALSE) {
                        $OrderModel->rollback();
                        $this->error('订单商品更新失败');
                        exit;
                    }
                }
            }

            // 删除订单商品
            foreach ($OrderProductList as $item) {
                if (!in_array($item['id'], $orderproid)) {
                    $OrderProductStatus = $OrderProductModel->destroy($item['id']);
                    if ($OrderProductStatus === FALSE) {
                        $OrderModel->rollback();
                        $this->error('订单商品删除失败');
                        exit;
                    }
                }
            }
            // foreach($OrderProductList as $item)
            // {

            // }

            // exit;

            // 商品表数据
            // $ProductData=[];

            // 商品表更新库存
            foreach ($productList as $item) {
                $product = $ProductModel->find($item['proid']);
                $nums = $item['nums'];
                $stock = $product['stock'];
                if (!isset($item['id'])) {
                    // echo '库存减少';
                    // break;
                    $UpdateStock = bcsub($stock, $nums);
                    if ($UpdateStock < 0) {
                        $this->error('商品库存不足');
                        exit;
                    } else {
                        $ProductData = [
                            'id' => $item['proid'],
                            'stock' => $UpdateStock,
                        ];
                        $ProductStatus = $ProductModel->isUpdate(true)->save($ProductData);
                        if ($ProductStatus === FALSE) {
                            $OrderProductModel->rollback();
                            $OrderModel->rollback();
                            $this->error('商品更新失败');
                            exit;
                        }
                    }

                } else {
                    // echo $item['id'].'库存怎加或减少';
                    // break;
                    $OrderProduct = $OrderProductModel->find($item['id']);
                    if ($item['nums'] < $OrderProduct['pronum']) {
                        $UpdateNum = bcsub($OrderProduct['pronum'], $item['nums']);
                        $UpdateStock = bcadd($stock, $UpdateNum);
                        $ProductData = [
                            'id' => $item['proid'],
                            'stock' => $UpdateStock,
                        ];
                        $ProductStatus = $ProductModel->isUpdate(true)->save($ProductData);
                        if ($ProductStatus === FALSE) {
                            $OrderProductModel->rollback();
                            $OrderModel->rollback();
                            $this->error('商品更新失败');
                            exit;
                        }
                    } else {
                        $UpdateNum = bcsub($item['nums'], $OrderProduct['pronum']);
                        $UpdateStock = bcsub($stock, $UpdateNum);
                        $ProductData = [
                            'id' => $item['proid'],
                            'stock' => $UpdateStock,
                        ];
                        $ProductStatus = $ProductModel->isUpdate(true)->save($ProductData);
                        if ($ProductStatus === FALSE) {
                            $OrderProductModel->rollback();
                            $OrderModel->rollback();
                            $this->error('商品更新失败');
                            exit;
                        }
                    }

                }
            }

            foreach ($OrderProductList as $item) {
                if (!in_array($item['id'], $orderproid)) {
                    $product = $ProductModel->find($item['proid']);
                    $pronum = $item['pronum'];
                    $stock = $product['stock'];
                    $UpdateStock = bcadd($pronum, $stock);
                    $ProductData = [
                        'id' => $item['proid'],
                        'stock' => $UpdateStock,
                    ];
                    $ProductStatus = $ProductModel->isUpdate(true)->save($ProductData);
                    if ($ProductStatus === FALSE) {
                        $OrderProductModel->rollback();
                        $OrderModel->rollback();
                        $this->error('商品更新失败');
                        exit;
                    }
                }
            }
            // exit;
            if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE) {
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('编辑失败');
                exit;
            } else {
                $OrderModel->commit();
                $OrderProductModel->commit();
                $ProductModel->commit();
                $this->success('编辑成功');
                exit;
            }

        }

        return $this->view->fetch();
    }

    public function address()
    {
        if ($this->request->isAjax()) {
            $busid = $this->request->param('busid', 0, 'trim');
            // halt($busid);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where = [
                'busid' => $busid,
            ];
            $total = $this->AddressModel
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->AddressModel
                ->with(['business'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // halt(collection($list)->toArray());
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $order = $this->OrderModel->find($ids);
        if (!$order) {
            $this->error(__('No Results were found'));
            exit;
        }
        $result = $this->OrderModel->destroy($ids);
        if ($result === FALSE) {
            $this->error('删除订单失败');
            exit;
        } else {
            $this->success('删除订单成功');
            exit;
        }

    }

    /**
     * 确认发货
     */
    public function send($ids = null)
    {
        if ($this->request->isAjax()) {
            $order = $this->OrderModel->find($ids);
            $express = $this->ExpressqueryModel->find();
            $expresscode = build_code();
            // halt($expresscode);
            // halt($express->toArray());
            // exit;
            if (!$order) {
                $this->error(__('No Results were found'));
                exit;
            }
            $data = [
                'id' => $ids,
                'status' => '2',
                'shipmanid' => $this->auth->id,
                'expressid' => $express['id'],
                'expresscode' => $expresscode
            ];
            $result = $this->OrderModel->isUpdate(true)->save($data);
            if ($result === FALSE) {
                $this->error('确认发货失败');
                exit;
            } else {
                $this->success();
                exit;
            }
        }
    }

    /**
     * 撤销发货
     */
    public function cancel($ids = null)
    {
        if ($this->request->isAjax()) {
            $order = $this->OrderModel->find($ids);
            if (!$order) {
                $this->error(__('No Results were found'));
                exit;
            }
            $data = [
                'id' => $ids,
                'status' => '1',
                // 'shipmanid'=>$this->auth->id
            ];
            $result = $this->OrderModel->isUpdate(true)->save($data);
            if ($result === FALSE) {
                $this->error('撤销发货失败');
                exit;
            } else {
                $this->success();
                exit;
            }
        }
    }

    /**
     * 订单详情
     */
    public function info($ids = null)
    {
        $row = $this->OrderModel->with(['business', 'address'])->find($ids);
        // halt($row->toArray());
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        $where = [
            'id' => $row['businessaddrid'],
            'busid' => $row['busid']
        ];
        $address = $this->AddressModel->where($where)->find();
        if (!$address) {
            $this->error('收货地址不存在');
            exit;
        }
        $OrderProductList = $this->OrderProductModel->where('orderid', $row['id'])->select();


        // $OrderProductData = [];
        foreach ($OrderProductList as $item) {
            $product = $this->ProductModel->with(['type', 'unit'])->find($item['proid']);
            $item['product'] = $product;
        }
        // halt($row->toArray());
        // halt(collection($OrderProductList)->toArray());
        $this->view->assign([
            'row' => $row,
            'OrderProductList' => $OrderProductList,
        ]);
        return $this->view->fetch();
    }

    /**
     * 查看物流
     */
    // 查看物流
    public function express($ids)
    {

        // 先判断订单是否存在
        $order = $this->OrderModel->find($ids);
        // $list=$this->OrderProductModel->where(['orderid'=>$ids])->select();
        // halt(collection($data)->toArray());
        // exit;
        // $this->assign([
        //     'list'=>$list,
        // ]);
       
        // halt($order->toArray());
        // exit;
        if (!$order) {
            $this->error('订单不存在');
            exit;
        }

        // 先获取物流单号
        $code = empty($order['expresscode']) ? '' : $order['expresscode'];

        if (empty($code)) {
            $this->error('快递单号为空，无法查询物流');
            exit;
        }

        // 调用物流接口
        $url = "https://wuliu.market.alicloudapi.com/kdi?no=$code"; //api访问链接

        // 请求信息
        $appcode = "6c5d6f10546c41939ec96b74c935e661";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);

        //初始化接口curl请求
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);

        // https 请求的验证
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        // 执行发起请求
        $out_put = curl_exec($curl);

        // 获取结果信息
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);

        if ($httpCode != 200) {
            $this->error('查询物流接口失败');
            exit;
        }

        $result = json_decode($body, true);

        $list = isset($result['result']['list']) ? $result['result']['list'] : [];
        $expName = isset($result['expName']) ? $result['expName'] : '';
        $courier = isset($result['courier']) ? $result['courier'] : '';
        $courierPhone = isset($result['courierPhone']) ? $result['courierPhone'] : '';


        // 组装数据
        $data = [
            'list' => $list,
            'expName' => $expName,
            'courier' => $courier,
            'courierPhone' => $courierPhone,
        ];
        $this->assign([
            'list'=>$list,
        ]);
        // if (empty($list)) {
        //     $this->error('未查询到物流记录');
        //     exit;
        // } else {
        //     $this->success('查询物流信息成功', null, $data);
        //     exit;
        // }
        return $this->view->fetch();
    }

    /**
     * 回收站
     */
    public function recycle()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->OrderModel
                ->onlyTrashed()
                ->with(['business', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->OrderModel
                ->onlyTrashed()
                ->with(['business', 'admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo $this->OrderModel->getlastSql();
            // exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 还原
     */
    public function restore($ids = null)
    {
        $row = $this->OrderModel->onlyTrashed()->where(['id' => ['in', $ids]])->select();

        if (!$row) {
            $this->error(__('请选择需要还原记录'));
        }

        $result = $this->OrderModel->onlyTrashed()->where(['id' => ['in', $ids]])->update(['deletetime' => null]);

        if ($result != true) {
            $this->error(__('还原失败'));
        } else {
            $this->success();
        }
    }

    /**
     * 真正删除
     */
    public function destroy($ids = null)
    {
        $ids = empty($ids) ? [] : explode(',', $ids);
        // halt($ids);
        // exit;
        $OrderProductData = [];
        foreach ($ids as $item) {
            $order = $this->OrderModel->onlyTrashed()->find($item);
            if (!$order) {
                $this->error('未找到该订单');
                exit;
            }
            $OrderProduct = $this->OrderProductModel->where(['orderid' => $order['id']])->column('id');
            // var_dump(collection($OrderProduct)->toArray());
            // array_push($OrderProductData,$OrderProduct);

            // 合并多个数组
            $OrderProductData = array_merge($OrderProductData, $OrderProduct);
        }
        // halt(collection($OrderProductData)->toArray());
        // $OrderProid=implode(',', $OrderProductData);
        // halt($OrderProid);
        $OrderStatus = $this->OrderModel->destroy($ids, true);
        if ($OrderStatus === FALSE) {
            $this->error($this->OrderModel->getError());
            exit;
        }

        // 同时删除订单商品
        $OrderProductStatus = $this->OrderProductModel->destroy($OrderProductData);
        if ($OrderProductStatus === FALSE) {
            $this->error($this->OrderProductModel->getError());
            exit;
        }
        if ($OrderStatus === FALSE || $OrderProductStatus === FALSE) {
            $this->error('订单删除失败');
            exit;
        } else {
            $this->success('订单删除成功');
            exit;
        }
    }
}